package com.example.smart_lock_app.data.repository

import com.example.smart_lock_app.data.model.LockLog
import com.example.smart_lock_app.data.model.LockState
import com.example.smart_lock_app.data.model.LockStatus
import kotlinx.coroutines.flow.*
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class LockRepositoryImpl @Inject constructor(
    // 预留MQTT管理器
    // private val mqttClientManager: MqttClientManager
) : LockRepository {

    private val _lockState = MutableStateFlow(LockState(LockStatus.SLEEP, "休眠"))
    private val _logs = MutableStateFlow<List<LockLog>>(emptyList())

    override suspend fun getLockState(): LockState = _lockState.value

    override suspend fun unlock(): Result<Unit> = try {
        // 预留MQTT通信代码
        _lockState.value = LockState(LockStatus.OPENED, "成功开启")
        addLog("远程开锁", LockStatus.OPENED)
        Result.success(Unit)
    } catch (e: Exception) {
        Result.failure(e)
    }

    override suspend fun lock(): Result<Unit> = try {
        _lockState.value = LockState(LockStatus.SLEEP, "休眠")
        addLog("休眠", LockStatus.SLEEP)
        Result.success(Unit)
    } catch (e: Exception) {
        Result.failure(e)
    }

    override fun observeLockState(): Flow<LockState> = _lockState
    override fun getLockLogs(): Flow<List<LockLog>> = _logs

    override suspend fun refreshLockState() {
        // 预留MQTT通信代码
        _lockState.value = LockState(LockStatus.START, "启动")
        addLog("系统启动", LockStatus.START)
    }

    private fun addLog(action: String, status: LockStatus) {
        val log = LockLog(
            id = System.currentTimeMillis().toString(),
            action = action,
            timestamp = System.currentTimeMillis(),
            status = status
        )
        _logs.update { currentLogs -> (listOf(log) + currentLogs).take(20) }
    }
} 